import React, { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardHeader, CardTitle, CardContent, CardFooter } from '@/components/ui/card';
import { Copy, RefreshCw, Terminal } from 'lucide-react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import OpenAIClient from '@/lib/llm';
import ReactMarkdown from 'react-markdown';
import rehypeHighlight from 'rehype-highlight';
import 'highlight.js/styles/atom-one-dark.css';

const LinuxCommandGenerator = () => {
  const [input, setInput] = useState('');
  const [output, setOutput] = useState('');
  const [distro, setDistro] = useState('ubuntu'); // 默认选择Ubuntu
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const generateCommand = async () => {
    if (!input.trim()) {
      setError('请输入需求描述');
      return;
    }
    
    setLoading(true);
    setError('');
    
    try {
      const openai = new OpenAIClient();
      const prompt = `为${distro} Linux生成以下需求的命令: ${input}`;
      
      const response = await openai.chat([
        {
          role: 'system',
          content: `你是一个专业的Linux命令生成器，能够根据用户需求生成${distro} Linux系统的命令。
          确保命令语法正确，并包含必要的解释注释。`+'并且建议以注释格式写出或者echo 意见或者建议，然后不要用``` ```'
        },
        {
          role: 'user',
          content: prompt
        }
      ], {
        temperature: parseFloat(import.meta.env.VITE_TEMPERATURE) || 0.2
      });
      
      setOutput(response);
    } catch (error) {
      console.error('命令生成错误:', error);
      setError('命令生成失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  const copyToClipboard = () => {
    navigator.clipboard.writeText(output);
  };

  return (
    <Card className="h-full flex flex-col">
      <CardHeader className="pb-3">
        <div className="flex items-center gap-3">
          <Terminal className="text-yellow-500" size={24} />
          <CardTitle>Linux命令生成器</CardTitle>
        </div>
      </CardHeader>
      <CardContent className="flex-1 grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 左侧输入区域 */}
        <div className="space-y-4">
          <div>
            <label className="block mb-2 text-sm font-medium">Linux发行版</label>
            <Select value={distro} onValueChange={setDistro}>
              <SelectTrigger className="w-full">
                <SelectValue placeholder="选择Linux发行版" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="ubuntu">Ubuntu</SelectItem>
                <SelectItem value="debian">Debian</SelectItem>
                <SelectItem value="centos">CentOS</SelectItem>
                <SelectItem value="fedora">Fedora</SelectItem>
                <SelectItem value="arch">Arch Linux</SelectItem>
                <SelectItem value="kali">Kali Linux</SelectItem>
              </SelectContent>
            </Select>
          </div>
          
          <div>
            <label className="block mb-2 text-sm font-medium">输入需求描述</label>
            <Textarea
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder="例如：安装网络扫描工具"
              className="min-h-[200px]"
            />
          </div>
          
          <div className="bg-gray-50 p-4 rounded-lg">
            <h3 className="text-sm font-medium mb-2">使用提示</h3>
            <ul className="text-xs text-gray-600 space-y-1 list-disc pl-5">
              <li>描述你想要完成的任务或操作</li>
              <li>系统将自动生成对应的Linux命令</li>
              <li>支持Ubuntu、CentOS等主流发行版</li>
              <li>生成的命令可直接在终端运行</li>
            </ul>
          </div>
        </div>
        
        {/* 右侧输出区域 */}
        <div className="flex flex-col">
          <label className="block mb-2 text-sm font-medium">生成的命令</label>
          <div className="relative flex-1">
            <div className="bg-gray-900 rounded-md p-4 text-sm overflow-auto h-full">
              {loading && <div className="text-green-400">生成中...</div>}
              {error && <div className="text-red-500">{error}</div>}
              {output ? (
                <div className="prose prose-dark max-w-none">
                  <ReactMarkdown rehypePlugins={[rehypeHighlight]}>
                    {`\`\`\`bash\n${output}\n\`\`\``}
                  </ReactMarkdown>
                </div>
              ) : (
                <span className="text-gray-500">生成的命令将显示在这里...</span>
              )}
            </div>
            {output && !loading && (
              <Button 
                size="icon" 
                variant="ghost" 
                className="absolute top-2 right-2 bg-gray-800 hover:bg-gray-700 text-white"
                onClick={copyToClipboard}
              >
                <Copy size={16} />
              </Button>
            )}
          </div>
        </div>
      </CardContent>
      <CardFooter>
        <Button 
          onClick={generateCommand} 
          className="w-full bg-yellow-600 hover:bg-yellow-700"
          disabled={loading}
        >
          {loading ? (
            <RefreshCw className="mr-2 animate-spin" size={16} />
          ) : (
            <RefreshCw className="mr-2" size={16} />
          )}
          {loading ? '生成中...' : '生成命令'}
        </Button>
      </CardFooter>
    </Card>
  );
};

export default LinuxCommandGenerator;
